import { h, createApp } from 'vue'
import MessageComponent from '@/components/message/message.vue'

let messageInstance = null
let messageApp = null

const Message = {
  install(app) {
    if (messageInstance) return
    
    // #ifdef H5
    // H5平台使用Vue3的方式创建应用
    const messageContainer = document.createElement('div')
    document.body.appendChild(messageContainer)
    
    // 创建一个新的Vue应用来挂载消息组件
    messageApp = createApp({
      data() {
        return {
          visible: false,
          message: '',
          type: 'info',
          position: 'center',
          duration: 2000
        }
      },
      methods: {
        show(options) {
          this.message = options.message || ''
          this.type = options.type || 'info'
          this.position = options.position || 'center'
          this.duration = options.duration || 2000
          this.visible = true
          
          setTimeout(() => {
            this.hide()
          }, this.duration)
        },
        hide() {
          this.visible = false
        }
      },
      render() {
        return h(MessageComponent, {
          visible: this.visible,
          message: this.message,
          type: this.type,
          position: this.position,
          duration: this.duration
        })
      }
    })
    
    // 将主应用的provide传递给消息应用
    const provides = app._context.provides
    if (provides) {
      for (const key in provides) {
        messageApp.provide(key, provides[key])
      }
    }
    
    messageInstance = messageApp.mount(messageContainer)
    // #endif

    const messageTypes = ['success', 'warning', 'error', 'info']
    
    const $message = (options) => {
      if (typeof options === 'string') {
        options = { message: options }
      }
      
      // #ifdef MP-WEIXIN || APP
      // 微信小程序和App平台使用原生API
      const typeMap = {
        success: 'success',
        warning: 'none',
        error: 'none',
        info: 'none'
      }
      
      uni.showToast({
        title: options.message,
        icon: typeMap[options.type || 'info'],
        duration: options.duration || 2000,
        mask: options.mask || false,
        position: options.position === 'bottom' ? 'bottom' : 'center'
      })
      // #endif
      
      // #ifdef H5
      // H5平台使用自定义组件
      if (messageInstance) {
        messageInstance.show(options)
      } else {
        // 回退方案
        uni.showToast({
          title: options.message,
          icon: 'none',
          duration: options.duration || 2000
        })
      }
      // #endif
    }
    
    messageTypes.forEach(type => {
      $message[type] = (options) => {
        if (typeof options === 'string') {
          options = { message: options }
        }
        options.type = type
        return $message(options)
      }
    })
    
    app.config.globalProperties.$message = $message
    uni.$message = $message
  }
}

export default Message